//引入createSlice和 configureStore
// createAsyncThunk 是帮助我们实现异步操作的方法
import { createSlice, configureStore, createAsyncThunk } from '@reduxjs/toolkit'

import axios from 'axios'

// 创建一个异步的对象
export const asyncMsg = createAsyncThunk('zzz', () => {
  // 这个回调函数中实现异步操作,要求必须返回值是一个promise实例
  return axios.get(`/admin/hosp/hospital/show/622574cc36a9ba1be763dad8`)
})

// 创建slice对象
const countSlice = createSlice({
  name: 'xxx',
  initialState: { c: 0, msg: { hospital: { hosname: 'aaa' } }, isShow: false },
  reducers: {
    add(state, action) {
      state.c = state.c + action.payload
    },
    sub(state, action) {
      state.c = state.c - action.payload
    },
  },
  // 新增代码:
  // 为异步操作定义action
  extraReducers(builder) {
    builder.addCase(asyncMsg.pending, (state) => {
      console.log('正在异步操作')
      state.isShow = true
    })
    builder.addCase(asyncMsg.fulfilled, (state, action) => {
      console.log('成功', state, action)
      state.msg = action.payload.data.data
      state.isShow = false
    })
    builder.addCase(asyncMsg.rejected, (state, action) => {
      console.log('失败')
      state.isShow = false
    })
  },
})

// 创建store

export const store = configureStore({
  reducer: {
    count: countSlice.reducer,
  },
})

// 导出action
// add和sub是actionCreator
export const { add, sub } = countSlice.actions
